import http from './http.js'
import { apiConfig } from '@/config/api.config'

export const chatApi = {
  // 获取用户对话历史列表
  getUserConversations: (userId) => {
    return http.get(`/api/user/${userId}/conversations`)
  },

  // 获取用户收藏的对话列表
  getUserCollectedConversations: (userId) => {
    return http.get(`/api/conversations/user/${userId}/collected`)
  },

  // 分页获取用户对话历史
  getUserConversationsPaged: (userId, page = 1, pageSize = 12) => {
    return http.get(`/api/conversations/user/${userId}/paged`, {
      params: { page, pageSize }
    })
  },

  // 创建新对话
  createConversation: (data) => {
    return http.post('/api/conversations', data)
  },

  // 获取对话详情
  getConversation: (conversationId) => {
    return http.get(`/api/conversations/${conversationId}`)
  },

  // 获取对话的所有消息
  getConversationMessages: (conversationId) => {
    return http.get(`/api/messages/conversation/${conversationId}`)
  },

  // 删除对话
  deleteConversation: (conversationId) => {
    return http.delete(`/api/conversations/${conversationId}`)
  },

  // 删除对话
  deleteConversation: (conversationId) => {
    return http.delete(`/api/conversations/${conversationId}`)
  },

  // 收藏/取消收藏对话
  setCollectConversation: (conversationId, isCollect = true) => {
    return http.post(`/api/conversations/${conversationId}/collect?isCollect=${isCollect}`, null)
  },

  // 发送消息
  sendMessage: (data) => {
    return http.post('/api/chat/ask', data)
  },

  // 发送流式消息
  sendMessageStream: async (data, onChunk, onError) => {
    const baseUrl = apiConfig.baseUrl; // 使用配置的API地址
    
    try {
      uni.request({
        url: `${baseUrl}/api/chat/ask-stream`,
        method: 'POST',
        header: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${uni.getStorageSync('token') || ''}`
        },
        data: {
          question: data.question,
          userId: data.userId,
          conversationId: data.conversationId,
          useRAG: data.useRAG || true,
          maxResults: data.maxResults || 5,
          similarityThreshold: data.similarityThreshold || 0.7
        },
        success: (response) => {
          if (response.statusCode === 200) {
            onChunk(response.data);
          } else {
            onError(new Error(`HTTP ${response.statusCode}`));
          }
        },
        fail: onError
      });
    } catch (error) {
      console.error('流式请求失败:', error);
      if (onError) {
        onError(error);
      }
    }
  },

  // 发送带文件的流式消息
  sendMessageStreamWithFiles: async (requestData, onChunk, onError) => {
    const baseUrl = 'http://localhost:5000'; // 后端API地址
    
    try {
      // 使用传入的普通对象
      const data = { ...requestData };
      
      uni.request({
        url: `${baseUrl}/api/chat/ask-stream-files`,
        method: 'POST',
        header: {
          'Authorization': `Bearer ${uni.getStorageSync('token') || ''}`
        },
        data: data,
        success: (response) => {
          if (response.statusCode === 200) {
            onChunk(response.data);
          } else {
            onError(new Error(`HTTP ${response.statusCode}`));
          }
        },
        fail: onError
      });
    } catch (error) {
      console.error('带文件的流式请求失败:', error);
      if (onError) {
        onError(error);
      }
    }
  },

  // 获取聊天历史
  getChatHistory: (page = 1, limit = 20) => {
    return http.get('/api/chat/history', {
      params: { page, limit }
    })
  },

  // 清除聊天历史
  clearChatHistory: () => {
    return http.delete('/api/chat/history')
  }
}

export default chatApi
